package cn.edu.gzist.rabbit.rabbitmqclient;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

public class ProducerRouter {
    //交换机名称
    static final String DIRECT_EXCHANGE="direct_exchange";
    //队列名称
    static final String DIRECT_QUEUE_INSERT="direct_queue_insert";
    //队列名称
    static final String DIRECT_QUEUE_UPDATE="direct_queue_update";

    public static void main(String[] args) throws Exception {
        //创建连接
        /** 1.创建新的连接 */
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        factory.setPort(5672);
        factory.setUsername("guest");
        factory.setPassword("guest");
        factory.setVirtualHost("/");
        Connection connection = factory.newConnection();
        //创建channel
        Channel channel = connection.createChannel();

        //声明交换机
        /**
         * 参数1：交换机名称
         * 参数2：交换机类型fanout，topic，direct，headers
         */
        channel.exchangeDeclare(DIRECT_EXCHANGE, BuiltinExchangeType.DIRECT);

        //声明队列
        /**
         * 参数一：队列名称
         * 参数二：是否定义持久化队列
         * 参数三：是否独占本次连接
         * 参数四：会否在不使用的时候自动删除队列
         * 参数五：队列其他参数
         */
        channel.queueDeclare(DIRECT_QUEUE_INSERT, true, false, false, null);
        channel.queueDeclare(DIRECT_QUEUE_UPDATE, true, false, false, null);

        //对垒绑定交换机 S2是RoutingKey
//        channel.queueBind(DIRECT_QUEUE_INSERT, DIRECT_EXCHANGE, "insert");
//        channel.queueBind(DIRECT_QUEUE_UPDATE, DIRECT_EXCHANGE, "update");

        //4.通过Channel发送数据
        String msg = "新增商品，路由模式RoutingKey为insert";
        /**
         * 参数1：交换机名称
         * 参数2：routingkey
         * 参数3：消息其他属性
         * 参数4：消息内容 byte[]
         */
        channel.basicPublish(DIRECT_EXCHANGE, "insert", null, msg.getBytes());
        System.out.println("已发送消息：" + msg);

        //发送消息
        msg = "修改了商品。路由模式：routingkey为update";
        /**
         * 参数1：交换机名称
         * 参数2：routingkey
         * 参数3：消息其他属性
         * 参数4：消息内容 byte[]
         */
        channel.basicPublish(DIRECT_EXCHANGE, "update", null, msg.getBytes());
        System.out.println("已发送消息：" + msg);


        //关闭连接
        channel.close();
        connection.close();
    }
}
